﻿using System.Diagnostics;
using System.IO;
using ClosedXML.Excel;
using Haimen.Excel;

namespace HmLab.Func1;

internal class LbResolveResultPath {

  /// <summary>
  /// ResolveResultTemplate
  /// <see cref="Haimen.Func1.ResultInputFiller"/>
  /// </summary>
  public void Run() {
    string resDir = @"E:\work_etc\nina\2023haimen2\workshop_cs\haimen\resources";
    string inDir = @"E:\work_etc\nina\2023haimen2\workshop_cslab\输O入0203";

    AppEnvPath envPath = _envResolver.Resolve(resDir, inDir);
    string[] groupList = ["W本周"];

    string resultTpl = ResolveResultTemplate(envPath, groupList);
    Debug.Assert(File.Exists(resultTpl));
    System.Console.WriteLine(resultTpl);
  }

  string ResolveResultTemplate(AppEnvPath path, string[] groups) {
    const string result = "result.xlsx";
    string dev = path.InDev(result);
    if (!File.Exists(dev)) {
      return path.ResFunc1(result);
    }

    System.Console.WriteLine($"检测到dev：{dev}");
    using FileStream stream = _excelUtil.OpenRead(dev);
    using XLWorkbook resultBook = new(stream);

    foreach (string group in groups) {
      IXLWorksheet sheet = resultBook.Worksheet(group);
      int rowCount = sheet.LastRowUsed().RowNumber();

      //TODO: 直接帮删
      if (rowCount != 2) {
        throw new System.Exception(
          $"结果模板数据源只允许存在一行！(Sheet：{group}，总行数：{rowCount})");
      }
    }

    return dev;
  }

  readonly LbResolveEnvirPath.Resolver _envResolver = new(new());
  readonly ExcelFileUtils _excelUtil = new();
}
